package org.fast.develop.logicflow.runtime.convert.builder.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.Data;
import org.fast.develop.logicflow.builder.AbstractLogicFlowNodeBuilder;
import org.fast.develop.logicflow.core.meta.base.Resource;
import org.fast.develop.logicflow.core.meta.exception.LogicFlowMetaException;
import org.fast.develop.logicflow.core.meta.shape.Start;
import org.fast.develop.logicflow.runtime.convert.builder.DesignerModelBuilder;
import org.fast.develop.logicflow.runtime.convert.designer.model.DesignerNodeModel;

import java.util.List;
import java.util.Objects;

/**
 * @author czh
 * @version V1.0
 * @data Created on 2022-12-31 10:18
 */
@Data
public class DesignerStartModelBuilder implements DesignerModelBuilder<DesignerNodeModel> {

    private final String DEFAULT_NAME = "开始";

    private DesignerNodeModel designerModel;

    private AbstractLogicFlowNodeBuilder logicFlowBuilder;

    @Override
    public AbstractLogicFlowNodeBuilder convert() {
        if (Objects.nonNull(this.getDesignerModel()) && Objects.nonNull(this.getLogicFlowBuilder())) {
            String name = DEFAULT_NAME;
            if (Objects.nonNull(designerModel.getText()) && designerModel.getText().containsKey("value")) {
                name = (String) designerModel.getText().get("value");
            }
            return logicFlowBuilder
                    .startEvent(designerModel.getId())
                    .name(name);
        } else {
            throw new LogicFlowMetaException("节点信息缺失");
        }

    }

    @Override
    public String getType() {
        return "start";
    }

    @Override
    public void convert(List<JSONObject> jsonObjects, Resource resource) {
        Start start = (Start) resource;
        JSONObject startObj = new JSONObject();
        startObj.set("type", getType());
        startObj.set("resourceId", start.getResourceId());
        JSONArray outgoing = new JSONArray();
        start.getOutgoing().forEach(item -> {
            outgoing.add(new JSONObject().set("resourceId", item.getResourceId()));
        });
        startObj.set("outgoing", outgoing);
        jsonObjects.add(startObj);
    }
}
